#include <QCoreApplication>

#include "autoupdatefile.h"

QString formatSize(qint64 bytes)
{
    QString strUnit;
    double dSize = bytes*1.0;
    if(dSize <= 0)
    {
        dSize = 0.0;
    }
    else if (dSize < 1024) {
        strUnit = "Bytes";
    }
    else if (dSize < 1024*1024) {
        dSize /= 1024;
        strUnit = "KB";
    }
    else if (dSize < 1024*1024*1024) {
        dSize /= (1024*1024);
        strUnit = "MB";
    }
    else {
        dSize /= (1024*1024*1024);
        strUnit = "GB";
    }

    return  QString("%1 %2").arg(QString::number(dSize, 'f', 2)).arg(strUnit);
}

QString speed(double speed)
{
    QString strUnit;
    if(speed <= 0)
    {
        speed = 0.0;
        strUnit = "Bytes/s";
    }
    else if (speed < 1024) {
        strUnit = "Bytes/s";
    }
    else if (speed < 1024*1024) {
        speed /= 1024;
        strUnit = "KB/s";
    }
    else if (speed < 1024*1024*1024) {
        speed /= (1024*1024);
        strUnit = "MB/s";
    }
    else {
        speed /= (1024*1024*1024);
        strUnit = "GB/s";
    }

    return  QString("%1 %2").arg(QString::number(speed, 'f', 2)).arg(strUnit);
}

QString timeFormat(int seconds)
{
    return QString("%1:%2:%3").arg(seconds/3600).arg(seconds/60%60).arg(seconds%60);
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    AutoUpdateFile *up = new AutoUpdateFile();
    up->setFilePath(qApp->applicationDirPath());
    QObject::connect(up, &AutoUpdateFile::downloadProgress, [](const DownloadInfo* downloadInfo){
        qDebug() << formatSize(downloadInfo->bytesReceived) << "/" << formatSize(downloadInfo->bytesTotal);
        qDebug() << speed(downloadInfo->speed) << timeFormat(downloadInfo->leftTime);
    });
    QObject::connect(up, &AutoUpdateFile::downloadFinished, [up](int stateCode){
        qDebug() << "downloadFinished" << stateCode;
        up->unzipFile();
    });
    QObject::connect(up, &AutoUpdateFile::downloadError, [](const QString& error){
        qDebug() << "downloadError" << error;
    });

    QObject::connect(up, &AutoUpdateFile::replyFinished, [up](QByteArray array){
        qDebug() << QString(array);
        up->startDown(QUrl("https://sm.myapp.com/original/Development/DebugView-4.81.0.0.zip"));
    });
    QObject::connect(up, &AutoUpdateFile::replyError, [](QVariant stateCode){
        qDebug() << "replyError" << stateCode;
    });

    up->requestUrl(QUrl("https://pc.qq.com/detail/2/detail_18522.html"));

    //up->startDown(QUrl("https://download.qt.io/archive/qt/6.3/6.3.0/single/qt-everywhere-src-6.3.0.zip"));
    //up->startDown(QUrl("https://slproweb.com/download/Win32OpenSSL-1_1_1n.exe"));

    return a.exec();
}
